<template>
    <div class="register-view">
        <div class="register-container">
            <!-- 左侧装饰 -->
            <div class="register-banner">
                <div class="banner-content">
                    <h1 class="banner-title">
                        <el-icon>
                            <Reading />
                        </el-icon>
                        水土TU
                    </h1>
                    <p class="banner-subtitle">加入我们</p>
                    <p class="banner-desc">注册账号，开启精彩之旅</p>
                </div>
            </div>

            <!-- 右侧注册表单 -->
            <div class="register-form-wrapper">
                <el-card class="register-card" shadow="never">
                    <div class="form-header">
                        <h2>用户注册</h2>
                        <p>创建您的账号</p>
                    </div>

                    <el-form :model="userForm" :rules="rules" ref="formRef" @submit.prevent="registerFn" size="large">
                        <el-form-item prop="account">
                            <el-input v-model="userForm.account" placeholder="请输入账号" :prefix-icon="User" clearable />
                        </el-form-item>

                        <el-form-item prop="username">
                            <el-input v-model="userForm.username" placeholder="请输入用户名" :prefix-icon="UserFilled"
                                clearable />
                        </el-form-item>

                        <el-form-item prop="password">
                            <el-input v-model="userForm.password" type="password" placeholder="请输入密码"
                                :prefix-icon="Lock" show-password clearable />
                        </el-form-item>

                        <el-form-item prop="password2">
                            <el-input v-model="userForm.password2" type="password" placeholder="请确认密码"
                                :prefix-icon="Lock" show-password clearable />
                        </el-form-item>

                        <el-form-item prop="imgUrl" label="上传头像">
                            <el-upload class="avatar-uploader" action="#" :show-file-list="false"
                                :before-upload="beforeAvatarUpload" :http-request="handleUpload" :auto-upload="false">
                                <el-avatar v-if="preview" :src="preview" :size="100" class="avatar-preview" />
                                <div v-else class="avatar-upload-placeholder">
                                    <el-icon class="upload-icon">
                                        <Plus />
                                    </el-icon>
                                    <div class="upload-text">点击上传头像</div>
                                </div>
                            </el-upload>
                        </el-form-item>

                        <el-form-item>
                            <el-button type="primary" native-type="submit" :loading="loading" style="width: 100%"
                                size="large">
                                {{ loading ? '注册中...' : '注册' }}
                            </el-button>
                        </el-form-item>
                    </el-form>

                    <div class="form-footer">
                        <el-divider>
                            <span class="divider-text">其他操作</span>
                        </el-divider>
                        <div class="footer-links">
                            <router-link to="/login" class="link">
                                <el-icon>
                                    <Avatar />
                                </el-icon>
                                已有账号，马上登录
                            </router-link>
                            <router-link to="/home" class="link">
                                <el-icon>
                                    <HomeFilled />
                                </el-icon>
                                返回首页
                            </router-link>
                        </div>
                    </div>
                </el-card>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { register, uploadPhoto } from '@/api/index'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules, UploadProps } from 'element-plus'
import { User, UserFilled, Lock, Plus, Avatar, HomeFilled, Reading } from '@element-plus/icons-vue'

const router = useRouter()
const formRef = ref<FormInstance>()
const loading = ref(false)
const file = ref<File>()
const preview = ref<string>('')
let imgUrl = ''

interface IUser {
    account: string
    password: string
    password2: string
    username: string
    imgUrl: string
}

const userForm = reactive<IUser>({
    account: "",
    password: "",
    password2: "",
    username: "",
    imgUrl: ""
})

const validatePass2 = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请再次输入密码'))
    } else if (value !== userForm.password) {
        callback(new Error('两次输入密码不一致'))
    } else {
        callback()
    }
}

const rules: FormRules = {
    account: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 3, max: 20, message: '账号长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    password2: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        { validator: validatePass2, trigger: 'blur' }
    ]
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    const isImage = rawFile.type.startsWith('image/')
    const isLt2M = rawFile.size / 1024 / 1024 < 2

    if (!isImage) {
        ElMessage.error('上传头像图片只能是图片格式!')
        return false
    }
    if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!')
        return false
    }

    file.value = rawFile

    // 本地预览
    const reader = new FileReader()
    reader.addEventListener('load', () => {
        preview.value = reader.result as string
    })
    reader.readAsDataURL(rawFile)

    return false // 阻止自动上传
}

const handleUpload = () => {
    // 手动上传逻辑会在提交表单时处理
    return Promise.resolve()
}

const registerFn = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
        if (!valid) return

        loading.value = true
        try {
            // 上传头像
            if (file.value) {
                const formData = new FormData()
                formData.append("photo", file.value)
                const resData: any = await uploadPhoto(formData)
                if (resData.code == 200) {
                    imgUrl = resData.picUrl
                }
            }

            // 注册
            const { account, password, username } = userForm
            const resData: any = await register({ account, password, username, imgUrl })

            if (resData.code == 200) {
                ElMessage.success(resData.msg || '注册成功')

                ElMessageBox.confirm(
                    '注册成功！是否跳转到登录页面？',
                    '提示',
                    {
                        confirmButtonText: '去登录',
                        cancelButtonText: '返回首页',
                        type: 'success',
                    }
                ).then(() => {
                    router.push({ path: '/login' })
                }).catch(() => {
                    router.push({ path: '/home' })
                })
            } else {
                ElMessage.error(resData.msg || '注册失败')
            }
        } catch (error) {
            ElMessage.error('注册失败，请稍后重试')
        } finally {
            loading.value = false
        }
    })
}
</script>

<style lang="less" scoped>
@import "../assets/varable.less";

.register-view {
    min-height: 100vh;
    background: linear-gradient(135deg, @success-color 0%, lighten(@success-color, 35%) 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 40px 20px;
}

.register-container {
    display: flex;
    width: 100%;
    max-width: 1100px;
    min-height: 680px;
    background: @bg-white;
    border-radius: 20px;
    box-shadow: @shadow-lg;
    overflow: hidden;
}

.register-banner {
    flex: 1;
    background: linear-gradient(135deg, @success-color 0%, darken(@success-color, 10%) 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 60px;
    color: @text-white;
    position: relative;
    overflow: hidden;

    &::before {
        content: '';
        position: absolute;
        width: 200%;
        height: 200%;
        background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 1px, transparent 1px);
        background-size: 40px 40px;
        animation: float 20s linear infinite;
    }

    .banner-content {
        position: relative;
        z-index: 1;
        text-align: center;

        .banner-title {
            font-size: 48px;
            font-weight: bold;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 15px;

            .el-icon {
                font-size: 56px;
            }
        }

        .banner-subtitle {
            font-size: 28px;
            margin-bottom: 15px;
            opacity: 0.95;
        }

        .banner-desc {
            font-size: 16px;
            opacity: 0.85;
            line-height: 1.8;
        }
    }
}

@keyframes float {
    0% {
        transform: translate(0, 0);
    }

    100% {
        transform: translate(-40px, -40px);
    }
}

.register-form-wrapper {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 40px;
}

.register-card {
    width: 100%;
    max-width: 460px;
    border: none;

    :deep(.el-card__body) {
        padding: 40px;
    }

    .form-header {
        text-align: center;
        margin-bottom: 35px;

        h2 {
            font-size: 28px;
            font-weight: bold;
            color: @text-primary;
            margin-bottom: 10px;
        }

        p {
            color: @text-secondary;
            font-size: 14px;
        }
    }

    .el-form {
        .el-form-item {
            margin-bottom: 20px;

            &:last-of-type {
                margin-bottom: 0;
            }
        }

        :deep(.el-form-item__label) {
            font-weight: 500;
            color: @text-secondary;
        }
    }

    .avatar-uploader {
        width: 100%;

        :deep(.el-upload) {
            width: 100%;
            border: 2px dashed @border-color;
            border-radius: 8px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;

            &:hover {
                border-color: @primary-color;
            }
        }

        .avatar-preview {
            display: block;
        }

        .avatar-upload-placeholder {
            text-align: center;
            padding: 20px;

            .upload-icon {
                font-size: 40px;
                color: @text-light;
                margin-bottom: 10px;
            }

            .upload-text {
                color: @text-secondary;
                font-size: 14px;
            }
        }
    }

    .form-footer {
        margin-top: 25px;

        .divider-text {
            color: @text-light;
            font-size: 13px;
        }

        .footer-links {
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 15px;
            margin-top: 20px;

            .link {
                display: flex;
                align-items: center;
                gap: 6px;
                color: @success-color;
                text-decoration: none;
                font-size: 14px;
                transition: all 0.3s;

                &:hover {
                    color: darken(@success-color, 10%);
                    transform: translateX(3px);
                }

                .el-icon {
                    font-size: 16px;
                }
            }
        }
    }
}

// 响应式设计
@media (max-width: 992px) {
    .register-banner {
        display: none;
    }

    .register-form-wrapper {
        flex: none;
        width: 100%;
    }
}

@media (max-width: 768px) {
    .register-view {
        padding: 20px;
    }

    .register-container {
        min-height: auto;
        border-radius: 16px;
    }

    .register-form-wrapper {
        padding: 20px;
    }

    .register-card {
        :deep(.el-card__body) {
            padding: 30px 20px;
        }

        .form-header {
            margin-bottom: 30px;

            h2 {
                font-size: 24px;
            }
        }
    }
}

@media (max-width: 576px) {
    .register-view {
        padding: 15px;
    }

    .register-container {
        border-radius: 12px;
    }

    .register-card {
        :deep(.el-card__body) {
            padding: 25px 15px;
        }

        .form-footer {
            .footer-links {
                flex-direction: column;
                align-items: center;
            }
        }
    }
}
</style>
